<template>
  <li class="tree-item" :class="{expand: isExpand, 'no-child': !treeItemData[childrenKey] || treeItemData[childrenKey].length === 0}" @click="asasdasdadasd">
    <div class="tree-content" @click="_clickEvent">
      <div class="expand-arrow" @click.stop="expandTree()">
        <a-icon :component="require('@/assets/icon/arrow_down.svg')" />
      </div>
      <div class="tree-label text-over" :class="{'no-child': !treeItemData[childrenKey] || treeItemData[childrenKey].length === 0}">{{ treeItemData[nameKey] }}</div>
    </div>
    <ul v-if="treeItemData[childrenKey] && treeItemData[childrenKey].length > 0" class="sub-tree">
      <!-- 递归 -->
      <TreeItem
        v-for="(item,index) in treeItemData[childrenKey]"
        :key="uuid()+index"
        :tree-item-data="item"
        :tree-click-event="treeClickEvent"
        :name-key="nameKey"
        :children-key="childrenKey"
      />
    </ul>
  </li>
</template>

<script>
export default {
  name: 'TreeItem',
  props: {
    treeItemData: {
      type: Object,
      default() {
        return {};
      }
    },
    nameKey: {
      type: String,
      default: 'text'
    },
    childrenKey: {
      type: String,
      default: 'ftmAtaChapter'
    },
    // 节点点击事件
    treeClickEvent: {
      type: Function,
      default() {
        return function() {};
      }
    }
  },
  data() {
    return {
      // 节点是否展开
      isExpand: this.treeItemData.expand || false
    };
  },
  methods: {
    // 展开/收缩
    expandTree(flag) {
      if (!this.treeItemData[this.childrenKey] || this.treeItemData[this.childrenKey].length === 0) {
        return;
      }
      if (typeof flag === 'undefined') {
        flag = !this.isExpand;
      } else {
        flag = !!flag;
      }
      this.isExpand = flag;
    },
    // 创建一个唯一id
    uuid() {
      let str = Math.random().toString(32);
      str = str.substr(2);
      return str;
    },
    asasdasdadasd(e) {
      if (document.querySelector('.vue-tree-select')?.classList) {
        document.querySelector('.vue-tree-select').classList.remove('vue-tree-select');
      }
      e.target.classList.add('vue-tree-select');
    },
    // 节点点击事件
    _clickEvent() {
      // 如果有传递事件函数，则调用事件函数并传递当前节点数据及组件
      if (this.treeClickEvent && typeof this.treeClickEvent === 'function') {
        this.treeClickEvent(this.treeItemData, this);
      }
    }
  }
};
</script>
